package com.tarena.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tarena.bo.DeptDao;
import com.tarena.bo.EmpDao;
import com.tarena.bo.UserDao;
import com.tarena.util.FormUtils;
import com.tarena.vo.Dept;
import com.tarena.vo.Emp;
import com.tarena.vo.User;

/**
 * 
 * @author WangPeihu
 * @since 30/12/2009
 * @Team [Never give up]
 * @version 1.0 <br>
 *          1. emp_list :显示所有员工 <br>
 *          2. emp_add_form :添加员工的表单界面<br>
 *          4. emp_delete :删除一个员工<br>
 *          5. emp_update_form :更新一个员工请求地址<br>
 *          6. emp_update_detail :更新一个员工的表单界面<br>
 *          7. login_form: :登录表单界面<br>
 *          8. login :登录请求<br>
 */
@SuppressWarnings("serial")
public class ActionServlet extends HttpServlet {

	private static EmpDao ed = new EmpDao();
	private static DeptDao dd = new DeptDao();
	private static UserDao ud = new UserDao();
	private static final String prefix = "/emp/";

	/**
	 * @查看所有的员工信息
	 * @param request
	 * @param response
	 * @throws Exception
	 * @throws IOException
	 */
	private void empList(HttpServletRequest request,
			HttpServletResponse response) throws Exception, IOException {
		List<Emp> empList = ed.findAllEmp();
		request.setAttribute("empList", empList);
		RequestDispatcher rd = request
				.getRequestDispatcher("/WEB-INF/jsp/emp_list.jsp");
		rd.forward(request, response);
	}

	/**
	 * @登录方法
	 * @param request
	 * @param response
	 * @throws Exception
	 * @throws IOException
	 */
	private void login(HttpServletRequest request, HttpServletResponse response)
			throws Exception, IOException {
		User user = new User();
		FormUtils.populate(user, request);
		if (ud.validateUser(user)) {
			HttpSession session = request.getSession();
			session.setAttribute("user_key", user);
			response.sendRedirect("emp_list");
		} else {
			response.sendRedirect("login_form");
		}
	}

	/**
	 * @验证用户是否已经登录
	 * @param request
	 * @param response
	 * @return
	 */
	private boolean validate(HttpServletRequest request) {
		HttpSession session = request.getSession();
		Object user = session.getAttribute("user_key");
		if (user != null) {
			return true;
		}
		return false;
	}

	/**
	 * @删除员工方法
	 * @param request
	 * @param response
	 */
	private void deleteEmp(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			String[] empId = request.getParameterValues("empId");
			if (empId != null) {
				Integer[] empIdIntegers = new Integer[empId.length];
				for (int i = 0; i < empIdIntegers.length; i++) {
					empIdIntegers[i] = Integer.parseInt(empId[i]);
				}
				ed.deleteEmp(empIdIntegers);
				response.sendRedirect("emp_list");
			} else {
				response.sendRedirect("emp_list");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @添加员工页面请求处理方法
	 * @param request
	 * @param response
	 */
	private void addEmpForm(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			List<Dept> deptList = dd.findAllDept();
			request.setAttribute("deptList", deptList);
			RequestDispatcher rd = request
					.getRequestDispatcher("/WEB-INF/jsp/emp_add_form.jsp");
			rd.forward(request, response);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * @增加员工方法
	 * @param request
	 * @param response
	 */
	private void addEmp(HttpServletRequest request, HttpServletResponse response) {
		try {
			request.setCharacterEncoding("utf-8");
			Emp emp = new Emp();
			Dept dept = new Dept();
			emp.setDept(dept);
			FormUtils.populate(emp, request);
			if (emp.getDept() != null && emp.getHireDate() != null
					&& emp.getName() != null) {
				ed.addEmp(emp);
			}
			response.sendRedirect("emp_list");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @更新员工信息页面请求处理方法
	 * @param request
	 * @param response
	 */
	private void updateEmpForm(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			String empId = request.getParameter("id");
			if (empId != null) {
				Integer id = Integer.parseInt(empId);
				Emp emp = ed.findEmpById(id);
				List<Dept> deptList = dd.findAllDept();
				request.setAttribute("deptList", deptList);
				request.setAttribute("emp", emp);
				RequestDispatcher rd = request
						.getRequestDispatcher("/WEB-INF/jsp/emp_update_form.jsp");
				rd.forward(request, response);
			} else {
				response.sendRedirect("emp_list");
			}
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @更新一个员工信息
	 * @param request
	 * @param response
	 */
	private static void updateEmp(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			request.setCharacterEncoding("utf-8");
			request.setCharacterEncoding("utf-8");
			Emp emp = new Emp();
			Dept dept = new Dept();
			emp.setDept(dept);
			FormUtils.populate(emp, request);
			response.sendRedirect("emp_list");
			ed.udateEmp(emp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @用于处理客户端发来的各种请求，并返回
	 * 
	 */
	@Override
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String url = request.getRequestURI();
		String path = url.substring(url.indexOf(prefix) + prefix.length());
		System.out.println(path);

		/** 登录表单界面请求 */
		if ("login_form".equals(path)) {
			RequestDispatcher rd = request
					.getRequestDispatcher("/WEB-INF/jsp/login_form.jsp");
			rd.forward(request, response);
		}

		/** 登录+用户名密码 请求 */
		if ("login".equals(path)) {
			try {
				login(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		/** 查看员工列表请求 */
		if ("emp_list".equals(path)) {
			if (validate(request)) {
				try {
					empList(request, response);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				response.sendRedirect("login_form");
			}
		}

		/** 添加员工页面请求 */
		if ("emp_add_form".equals(path)) {
			if (validate(request)) {
				addEmpForm(request, response);
			} else {
				response.sendRedirect("login_form");
			}
		}

		/** 添加员工提交的请求 */
		if ("emp_add".equals(path)) {
			if (validate(request)) {
				addEmp(request, response);
			} else {
				response.sendRedirect("login_form");
			}
		}

		/** 删除员工请求 */
		if ("emp_delete".equals(path)) {
			if (validate(request)) {
				deleteEmp(request, response);
			} else {
				response.sendRedirect("login_form");
			}
		}

		/** 更新员工提交信息 */
		if ("emp_update".equals(path)) {
			if (validate(request)) {
				updateEmp(request, response);
			} else {
				response.sendRedirect("login_form");
			}
		}

		/** 更新员工页面请求 */
		if ("emp_update_form".equals(path)) {
			if (validate(request)) {
				updateEmpForm(request, response);
			} else {
				response.sendRedirect("login_form");
			}
		}
	}
}